﻿using JWT;
using JWT.Algorithms;
using JWT.Exceptions;
using JWT.Serializers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApiVersionControl.Models.Untity;

namespace WebApiVersionControl.Controllers
{
    public class AuthorController : Controller
    {
#pragma warning disable CS0414 // 字段“AuthorController.secret”已被赋值，但从未使用过它的值
        private static string secret = "yangjun";
#pragma warning restore CS0414 // 字段“AuthorController.secret”已被赋值，但从未使用过它的值
        private static string SecretKey = "ok";
        // GET: Author
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 通过密钥获取 Token
        /// </summary>
        /// <returns></returns>
        public string GetToken()
        {
            var payload = new Dictionary<string, dynamic>
                {
                    { "username","yangjun"},
                    {"password","123" }
                };
            IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
            IJsonSerializer serializer = new JsonNetSerializer();
            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
            IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
            payload.Add("timeout", DateTime.Now.AddMinutes(2));
            string Token = encoder.Encode(payload, SecretKey);
            return Token;
        }

        /// <summary>
        /// Token 解密
        /// </summary>
        /// <returns></returns>
        public string DecodeToken(string token)
        {
            string json = string.Empty;
            try
            {
                IJwtAlgorithm algorithm = new HMACSHA256Algorithm();//HMACSHA256加密
                IJsonSerializer serializer = new JsonNetSerializer();
                IDateTimeProvider provider = new UtcDateTimeProvider();
                IJwtValidator validator = new JwtValidator(serializer, provider);
                IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
                IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, algorithm);
                json = decoder.Decode(token, SecretKey, verify: true);
                //将字符串反向生成对应的对象类
                var result = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
                if ((DateTime)result["timeout"] < DateTime.Now)
                {
                    new Exception(message: "jwt已经过期，请重新登录");
                    result.Remove(key: "timeout");
                    return "Token已过期，请重新登录";
                }
            }
            catch (Exception)
            {
                return APIModel.error("Token过期了").ToString();
            }
            return json;
        }
    }
}